package org.yzh.scheduler.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.yzh.commons.model.APIResult;
import org.yzh.commons.util.JWTUtils;
import org.yzh.commons.util.NetUtils;
import org.yzh.scheduler.model.entity.UserDO;
import org.yzh.scheduler.model.enums.ResultCodes;
import org.yzh.scheduler.model.vo.Token;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetAddress;

@Api(description = "认证API")
@RestController
public class AuthController {

    @ApiOperation(value = "登陆")
    @PostMapping("auth/login")
    public APIResult<Token> login(@ApiParam(value = "用户名", required = true) @RequestParam Integer username,
                                  @ApiParam(value = "密码", required = true) @RequestParam String password) {
//        UserDO user = userService.get(username);
        UserDO user = new UserDO(1, "abc@123");
        if (user == null)
            return new APIResult(ResultCodes.NotFoundUser);
        if (!user.getPassword().equals(password))
            return new APIResult(ResultCodes.UsernameOrPasswordError);

        String token = JWTUtils.sign(user, 60 * 60 * 6);

        return new APIResult(new Token(token, username, user.getRole()));
    }

    @GetMapping("/")
    public void home(HttpServletResponse response) throws IOException {
        response.sendRedirect("home.html");
    }

    @GetMapping("/ip")
    public String ip() {
        InetAddress lanAddress = NetUtils.getLocalHostLANAddress();
        return "lanAddress: " + lanAddress;
    }
}